package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: HuangFu
 * @Date: 2020/2/1 15:49
 * @Description:
 */
@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private ESManagerMapper esManagerMapper;


    @Override
    public void createIndexAndMappering() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        //获取所有Sku,当参数为All
        List<Sku> skuList = skuFeign.findListBySpuId("all");
        if(skuList==null && skuList.size()<0){
            new RuntimeException("当前商品无数据");
        }
        improtDataBySkuList(skuList);
    }

    @Override
    public void importDataBySpuId(String spuId) {
        //获取所有Sku,当参数为All
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if(skuList==null && skuList.size()<0){
            new RuntimeException("当前商品无数据，无法导入索引库:"+spuId);
        }
        improtDataBySkuList(skuList);
    }

    @Override
    public void deleteDataBySpuId(String spuId) {
        //获取Sku列表数据
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if(skuList==null && skuList.size()<0){
            new RuntimeException("当前商品无数据，无法删除:"+spuId);
        }
        for (Sku sku : skuList) {
            //删除索引数据
            esManagerMapper.deleteById(Long.valueOf(sku.getId()));
        }
    }

    @Override
    public void deleteAll() {
        esManagerMapper.deleteAll();
    }

    private void improtDataBySkuList( List<Sku> skuList){
        //将SkuList数据转成SkuInfo存入索引库
        List<SkuInfo> skuInfoList = JSON.parseArray(JSON.toJSONString(skuList), SkuInfo.class);

        //循环转换规格数据
        for (SkuInfo skuInfo: skuInfoList ){
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //存入索引库
        esManagerMapper.saveAll(skuInfoList);
    }

}
